import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

import 'light_button.dart';

class ProgressView extends StatefulWidget {
  const ProgressView({Key? key}) : super(key: key);

  @override
  State<ProgressView> createState() => _ProgressViewState();
}

class _ProgressViewState extends State<ProgressView>
    with SingleTickerProviderStateMixin {
  //控制进度的动画
  AnimationController? _controller;
  Animation<double>? _animation;

  ui.Image? image;

  @override
  void initState() {
    //设置动画3秒，切将动画生命周期和当前组件绑定
    _controller = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );
    //设置动画值的变化（从0到1，默认线性变化）
    _animation = Tween<double>(begin: 0, end: 1).animate(_controller!)
      ..addListener(() {
        setState(() {});
      });
    //加载需要使用Canvas绘制的图片
    _initImage();

    super.initState();
  }

  @override
  void dispose() {
    //动画释放
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (image == null) {
      return Container(
        color: Colors.grey,
      );
    } else {
      debugPrint("scale:${_animation!.value}");
      return Container(
        color: Colors.grey,
        child: GestureDetector(
          onTap: () {
            //动画从0开始
            debugPrint("onTap");
            _controller?.forward(from: 0);
          },
          child: Stack(
            children: [
              CustomPaint(
                painter: ProgressCanvas(image!, _animation!.value),
              ),
              const Positioned(
                  left: 50,
                  top: 100,
                  child: Image(image: AssetImage("images/pic_recording_bg.png"))),
            ],
          ),
        ),
      );
    }
  }

  void _initImage() async {
    debugPrint("开始loadImage");
    final image = await loadImage("images/pic_record_progress_bg.png");
    debugPrint("图片加载完毕:${image.width}x${image.height}");
    setState(() {
      this.image = image;
    });
  }

}

///Canvas绘制进度
class ProgressCanvas extends CustomPainter {
  final ui.Image image;
  final double animationScale;

  ProgressCanvas(this.image, this.animationScale);

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    //开启canvas绘制的透明通道
    canvas.saveLayer(null, paint);
    //绘制灰色的非正圆进度背景
    canvas.drawImage(image, const Offset(40,90), paint);
    //接下来的绘制使用BlendMode为srcATop的模式，待绘制的内容和已绘制内容相交的区域，且内容显示为待绘制区域。
    paint.blendMode = BlendMode.srcATop;
    paint.color = const Color(0xFF09D17B);
    canvas.drawArc(Rect.fromLTWH(40-10,90-10, (image.width+20).toDouble(), (image.height+20).toDouble()), -90*pi/180, 360*animationScale*pi/180, true, paint);
    canvas.restore();
  }

  @override
  bool shouldRepaint(ProgressCanvas oldDelegate) {
    return oldDelegate.animationScale != animationScale;
  }
}
